package cn.marinda.util;

import cn.marinda.MinecraftServerHelper;
import cn.marinda.entity.Server;
import cn.marinda.gui.impl.TipsDialogImpl;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

public class FileUtils {

    /**
     * 附加文件文本注
     *
     * @param bufferedWriter 缓冲作家
     * @param note           请注意
     */
    public static void appendFileTextNote(BufferedWriter bufferedWriter, String note){
        try {
            bufferedWriter.write("#" + note);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 附加文件文本行
     */
    public static void appendFileTextLine(BufferedWriter bufferedWriter,String text){
        try {
            bufferedWriter.write(text + "\n");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 创建启动服务器批文件
     *
     * @return boolean
     */
    public static File createStartServerBat(Server serverDir,String fileName){
        File startBat = null;
        try {
            File dir = new File(serverDir.getPath());
            if (dir.isDirectory()) {
                if (!dir.exists()) {
                    dir.mkdir();
                }
            }
            startBat = new File("."+serverDir.getPath(), fileName);
            if (!startBat.exists()) {
                startBat.createNewFile();
            }
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return startBat;
    }

    /**
     * 编写开服bat内容
     *
     *
     * @param batFile bat文件
     * @param core    核心
     * @return boolean
     */
    public static boolean writeStartServerBat(File batFile,String core){
        try {
            FileWriter bufferedWriter = new FileWriter(batFile);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(batFile)));
            if (bufferedReader.readLine() != null) {
                bufferedWriter.write("java -Xms1024M -Xmx3096M -jar " + core + "\n");
                return false;
            }
            bufferedWriter.write("java -Xms1024M -Xmx3096M -jar " + core + "\n");
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
            return true;
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return true;
    }


    /**
     * 创建服务器相关目录
     *
     * @return boolean
     */
    public static void createServerDir(){
        for(Server server : Server.values()){
            String serverPath = server.getPath();
            if(serverPath.startsWith("./")){
                continue;
            }
            String replacePath = serverPath.replace("/","./");
            String path = replacePath;
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
        }
    }

    /**
     * 移动Core文件夹下的指定名称核心
     *
     * @return boolean
     */
    public static boolean moveCoreByName(String coreName){
        String corePath = "./core";
        File coreFile = new File(corePath,coreName);
        String serverPath = "./server";

        if(coreFile.exists()){
            coreFile.renameTo(new File(serverPath,coreName));
            return true;
        }
        return false;
    }

    /**
     * 移动服务器插件文件
     */
    public static void moveServerPluginFiles(){
        String fileName = "";
        try {
            String serverPluginPath = "." + Server.SERVER_DOWNLOAD_PLUGIN.getPath();
            String serverPath = "./server";
            String pluginsDir = serverPath + "/plugins";
            File serverPluginDir = new File(pluginsDir);
            if(!serverPluginDir.exists()){
                serverPluginDir.mkdirs();
            }
            File[] pluginList = new File(serverPluginPath).listFiles();
            for (File plugin : pluginList) {
                fileName = plugin.getName();
                String targetName = serverPath + "/plugins/" + fileName;
                plugin.renameTo(new File(targetName));
            }
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
    }

    /**
     * 移动服务器文件
     *
     * @return boolean
     */
    public static String moveServerCoreFiles(){
        String fileName = "";
        try {
            String serverCorePath = "./core";
            String serverPath = "./server";
            File[] coreList = new File(serverCorePath).listFiles();
//        移动ServerCore
            for (File core : coreList) {
                fileName = core.getName();
                String targetName = serverPath+"/"+fileName;
                core.renameTo(new File(targetName));
            }
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return fileName;
    }

    /**
     * 查询本地Server目录下的所有核心文件
     *
     * @return boolean
     */
    public static List<String> findServerLocationCores(){
        List<String> list = new ArrayList<>();
        String fileName = "";
        try {
            String serverPath = "./server";
            File[] coreList = new File(serverPath).listFiles();
//        移动ServerCore
            for (File core : coreList) {
                fileName = core.getName();
//                检索以jar结尾的核心
                if(!fileName.endsWith(".jar")){
                    continue;
                }
                list.add(fileName);
            }
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return list;
    }

    /**
     * 查询本地Core目录下的所有核心文件
     *
     * @return boolean
     */
    public static List<String> findLocationCores(){
        List<String> list = new ArrayList<>();
        String fileName = "";
        try {
            String serverPath = "./core";
            File[] coreList = new File(serverPath).listFiles();
//        移动ServerCore
            for (File core : coreList) {
                fileName = core.getName();
//                检索以jar结尾的核心
                if(!fileName.endsWith(".jar")){
                    continue;
                }
                list.add(fileName);
            }
        }catch (Exception e){

        }
        return list;
    }


    /**
     * 移动服务器配置
     */
    public static void moveServerConfig(){
//      移动服务器核心到server文件夹下
        String coreName = moveServerCoreFiles();
//        创建bat批处理文件进行控制
        File batFile = createStartServerBat(Server.SERVER_DIR, "start.bat");
        writeStartServerBat(batFile, coreName);
        try {
            MinecraftServerHelper.serverInfo.createEulaFile();
            MinecraftServerHelper.serverInfo.createServerPropertiesFile();
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
//        不直接开服！
//        MinecraftServerHelper.process.startBatServer("start.bat", Server.SERVER_DIR);
    }

    /**
     * 查询服务器核心存在
     *
     * @return boolean
     */
    public static boolean findServerCoreExists(){
        try {
            String path = Server.SERVER_DIR.getPath();
            File dir = new File(System.getProperty("user.dir")+"/"+path);
//            如果目录不存在或者这个目录下不存在文件
            if(!dir.exists()){
                return false;
            }
//            遍历
            for(File core : dir.listFiles()){
                String suffix = core.getName().substring(core.getName().indexOf(".")+1);
//                如果后缀不存在jar 直接false
                if(!suffix.equalsIgnoreCase("jar")){
                   continue;
                }
            }
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return true;
    }

    /**
     * 获得服务器bat核心名称
     *
     * @return {@link String}
     */
    public static String getServerBatCoreName(){
       File bat =  new File("."+Server.SERVER_DIR.getPath(),"start.bat");
       String coreName = "";
       try{

           FileInputStream inputStream = new FileInputStream(bat);
           byte[] bytes = new byte[inputStream.available()];
           int len = 0;
           while((len = inputStream.read(bytes)) != -1){
                String str = new String(bytes);
                System.out.println("core: " + str);
                int start = str.indexOf(".")-1;
//                防止有子版本参数进入
                int end = str.indexOf(".",start+2);
                coreName = str.substring(start,end);
           }
           inputStream.close();
       }catch (Exception e){
           e.printStackTrace();
       }
       return coreName;
    }

    /**
     * 获得服务器版本
     *
     * @param coreName 核心名字
     * @return {@link String}
     */
    public static String getServerVersion(String coreName){
        int start = coreName.indexOf(".")-1;
//                防止有子版本参数进入
        int end = coreName.indexOf(".",start+2);
        String version = coreName.substring(start,end);
        return version;
    }

    /**
     * 添加到高版本服务器bat
     */
    public static boolean appendToHightVersionServerBat(File batFile,String coreName){
        try {
            FileWriter bufferedWriter = new FileWriter(batFile);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(batFile)));
            if (bufferedReader.readLine() != null) {
                bufferedWriter.write("java -Xms1024M -Xmx3096M -jar "+coreName+ " --nogui \n");
                return false;
            }
            bufferedWriter.write("java -Xms1024M -Xmx3096M -jar " + coreName + " --nogui \n");
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
            return true;
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return false;
    }



    /**
     * 获取服务器核心名称
     *
     * @return {@link String}
     */
    public static String getServerCoreName(){
        String path = Server.SERVER_DIR.getPath();
        File dir = new File(path);
        if(dir.exists()){
            for(File file : dir.listFiles()){
                String fileName = file.getName();
                String prefix = fileName.substring(fileName.indexOf(".")+1);
                if(prefix.equalsIgnoreCase("jar")){
                    return fileName;
                }
            }
        }
        return null;
    }

}
